package com.learn.MoreThread;

public class TestThreadLocal {
    private static Index num = new Index();
    //创建一个Integer类型的线程本地变量
    public static final ThreadLocal<Index> local = new ThreadLocal<Index>(){
        protected  Index initialValue() {
            return num;
        }
    };

    public static void main(String[] args) {
        Thread[] thread = new Thread[5];
        for (int i=0;i<thread.length;i++) {
            thread[i] = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        Index index = local.get();
                        for(int j=0;j<thread.length;j++){
                            index.increase();
                        }
                        System.out.println(Thread.currentThread().getName()+":"+index.num);
                    }
                }
            );
        }
        for (Thread t: thread) {
            t.start();
        }
    }

    private static class Index {
        int num;
        public void increase() {
            num++;
        }
    }
}
